﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARNative;
using System.Web.Mvc;

namespace NRemedy.MVC.UI
{
    ////            routes.MapRoute(
    //            null, // Route name
    //            "Table/Query/{form}", // URL with parameters
    //            new { controller = "Table", action = "Query" } // Parameter defaults
    //        );    
    public class TableController : SessionController
    {
        [JsonExceptionHandler]
        public virtual ActionResult Query(string form, FormCollection TIdCollection, string qu)
        {
            TableRequest request = Parse(form, TIdCollection, qu);
            return QueryInternal(ARUserSession.ARContext, request);
        }

        [NonAction]
        public virtual ActionResult QueryInternal(ARLoginContext context, TableRequest request)
        {
            try
            {
                int totalMatch = 0;
                var entries = context.ServerInstance.GetEntryList(request.FormName,
                    request.Qualification, request.FieldIds,
                    request.StartIndex, request.RetrieveCount, ref totalMatch, request.Sorts);
                return JsonFromEntries(entries, totalMatch, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        [NonAction]
        public virtual TableRequest Parse(string form, FormCollection TIdCollection, string qu)
        {
            List<uint> fieldIds = new List<uint>();
            uint rows = 0;
            uint page = 0;
            string sort = null;
            string order = null;
            string fieldsStr = null;

            foreach (var key in TIdCollection.AllKeys)
            {
                if (key == "rows")
                    rows = Convert.ToUInt32(TIdCollection[key]);
                else if (key == "page")
                    page = Convert.ToUInt32(TIdCollection[key]);
                else if (key == "sort")
                    sort = TIdCollection[key];
                else if (key == "order")
                    order = TIdCollection[key];
                else if (key == "fields")
                    fieldsStr = TIdCollection[key];
            }

            //prepare fieldId list
            foreach (var id in fieldsStr.Split('|'))
            {
                if (string.IsNullOrEmpty(id)) continue;
                fieldIds.Add(Convert.ToUInt32(id));
            }


            //prepare sortorder
            List<ARSortInfo> arsi = null;
            if (sort != null && order != null)
            {
                ARSortInfo si = new ARSortInfo();
                if (order == "desc")
                    si.Order = SortOrder.SORT_DESCENDING;
                else
                    si.Order = SortOrder.SORT_ASCENDING;
                si.FieldId = Convert.ToUInt32(sort.Substring(1));
                arsi = new List<ARSortInfo>();
                arsi.Add(si);

            }
            TableRequest request = new TableRequest();
            request.FieldIds = fieldIds;
            request.FormName = form;
            request.Qualification = qu;
            request.RetrieveCount = rows;
            request.StartIndex = (page - 1) * rows;            
            request.Sorts = arsi;

            return request;
        }

        [NonAction]
        public virtual JsonResult JsonFromEntries(IEnumerable<AREntry> entries, int totalMatch, JsonRequestBehavior behavior)
        {
            //{total:xx,rows:[{fyyy:yyy,fzzz:zzz},{},{}]}
            if (entries == null)
                return null;
            JsonBuilder jbuilder = new JsonBuilder();
            jbuilder.MergeProperty("total", totalMatch);

            if (entries.Count() < 1)
                jbuilder.MergeProperty("rows", string.Empty);
            else
            {
                foreach (var entry in entries)
                {
                    JsonBuilder entrybuilder = new JsonBuilder();
                    foreach (var flv in entry.FieldValues)
                    {
                        entrybuilder.MergeProperty("f" + flv.FieldId, flv.Value);
                    }
                    jbuilder.MergeChildObject("rows", entrybuilder);
                }
            }

            return new RawJsonResult() { JsonRequestBehavior = behavior, Data = jbuilder.ToString() };
        }
    }
}
